package io.gitee.hechenl.datamultitrans.http.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Map;

@Component
public class HttpHelper {

    private static final int DEFAULT_MAX_ATTEMPTS = 3; // 重试间隔1.5秒
    private static final long DEFAULT_FIXED_BACKOFF = 1500; // 重试间隔1.5秒

    @Autowired
    private RestTemplate restTemplate;

    public <T> T get(String url, Map<String, ?> uriVariables, int maxAttempts, long fixedBackoff, Class<T> clazz) {
        return RetryTemplate.builder()
                .maxAttempts(Math.min(maxAttempts, DEFAULT_MAX_ATTEMPTS))
                .fixedBackoff(Math.min(fixedBackoff, DEFAULT_FIXED_BACKOFF))
                .retryOn(Arrays.asList(RestClientException.class))
                .build()
                .execute(context -> restTemplate.getForObject(url, clazz, uriVariables));
    }

    public <T> T post(String url, Object requestBody, int maxAttempts, long fixedBackoff, Class<T> clazz) {
        return RetryTemplate.builder()
                .maxAttempts(Math.min(maxAttempts, DEFAULT_MAX_ATTEMPTS))
                .fixedBackoff(Math.min(fixedBackoff, DEFAULT_FIXED_BACKOFF))
                .retryOn(Arrays.asList(RestClientException.class))
                .build()
                .execute(context -> restTemplate.postForObject(url, requestBody, clazz));
    }

}
